<template>
  <div class="common-fc extendClass" v-if="hasExpandAttr">
    <!-- <Divider orientation="left">{{$t('module.treeManage.ettrAtt')}}</Divider> -->
    <p class="extendedAttrTitle">{{$t('module.treeManage.ettrAtt')}}</p>
    <Form class="myForm" :label-width="options.form ? options.form.labelWidth || 100 : 100">
      <Form-item :label="$t('module.treeManage.selectModel')">
        <Select
          :disabled="!isEdit"
          v-model="ruleDataVal"
          :style="{ width: selectWidth }"
          :clearable="isClearable"
          transfer
          @on-clear="onClear"
          @on-change="changeRule">
          <Option
            v-for="item in ruleDatas"
            :value="item.id"
            :key="item.id"
            :style="{ color:(templateType== 'EMPLOYEE' || templateType== 'TREE_CODE') && item.status && item.status == 2?'#bcbcbc!important': '' }"
          >{{ item.templateName }}</Option>
        </Select>
        <div class="assign-tree-dimension" ref="treeRoot" v-if="isShowTip && ruleData.length == 0">
          <span class="operation-hint" style="margin-left: 0;">{{ $t("module.treeManage.templateNull") }}</span>
        </div>
      </Form-item>
    </Form>
    <form-create v-if="ruleDataVal" v-model="fcApi" :rule="ruleData" :option="option" class="create-form-wrap"></form-create>
  </div>
</template>
<script>
import { getTemplateList, templateDetail } from "@/api/extendAttrApi";
import { CoreModuleName } from "@/const";
import locales from "../locales.js";
export default {
  mixins: [locales],
  name: "FormCreateComponent",
  data: () => ({
    fcApi: {},
    ruleData: [],
    ruleDataVal: "",
    ruleDatas: [],
    hasExpandAttr: false, // 有数据则显示该组件
    onece: true,
    isShowTip: false,
    isFirst:true
  }),
  props: {
    isAdd: {
      type: Boolean,
      default: () => false
    },
    isEdit: {
      type: Boolean,
      default: () => true
    },
    isClearable: {
      type: Boolean,
      default: () => false
    },
    selectWidth: {
      type: String,
      default: "auto"
    },
    // 扩展设置
    options: {
      type: Object,
      default: () => ({})
    },
    rules: {
      type: Array,
      default: () => []
    },
    // 实力属性
    fApi: {
      type: Object,
      default: () => ({})
    },
    // 提交按钮
    submitBtn: {
      type: Boolean,
      default: false
    },
    // 模板id
    templateId: {
      type: String,
      default: ""
    },
    // 拓展属性类别
    templateType: {
      type: String,
      default: ""
    },
    // 现在是列表页面某一行的数据，其中包括了后端返回的 ext1 -ext20 的拓展字段
    attributeValue: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    option() {
      const { submitBtn, options } = this;

      return {
        ...options,
        resetBtn: false,
        submitBtn
      };
    }
  },
  created() {
    this.getInitTemplateId()
  },
  watch: {
    isAdd: function(val) {
      if(val) {
        this.ruleDataVal = ""
      }
    },
    fcApi: {
      handler: function(value) {
        this.$emit("update:fApi", this.fcApi);
      },
      immediate: true
    },
    attributeValue: {
      handler: function() {
        this.getTemplateHandler();
      },
      immediate: true
    },
    isEdit: {
      handler: function() {
        this.getTemplateHandler();
      },
      immediate: true
    },
    //当选择的模板下面属性为空时，提示在拓展属性中配置属性
    templateId: function(value) {
      if(value) {
        this.isShowTip = true
      }else {
        this.isShowTip = false
      }
    }
  },
  methods: {
    onClear () {
      this.fcApi.resetFields();
      this.fcApi = {}
    },
    setGlobalConfig(rules, conf) {
      for (const [key, val] of Object.entries(conf)) {
        rules.forEach(rule => {
          // if (rule.id) {
          //   delete rule.id;
          // }
          if (key === "*") {
            this.mergeLable(rule, val);
          } else if (key === rule.type) {
            this.mergeLable(rule, val);
          }
        });
      }
      if (true) {
        this.mergeValue(rules);
      }
      
      this.ruleData = rules;
      // 当表单为下拉框时，为下拉框增加搜索功能
      for(let i = 0; i < this.ruleData.length; i++) {
        if(this.ruleData[i].type == "select") {
          this.ruleData[i].props.filterable = true
        }
      }
      this.$emit("update:fApi", this.fcApi);
    },
    mergeLable(rule, target) {
      for (const [key, val] of Object.entries(target)) {
        // if (typeof rule[key] === 'object' && rule[key].id) {
        //   delete rule[key].id;
        // }
        rule[key] ? rule[key] : (rule[key] = {});
        const disabled = rule[key].disabled ? rule[key].disabled : val.disabled;
        Object.assign(rule[key], val);
        if (disabled) {
          rule[key].disabled = disabled;
        }
      }
    },
    mergeValue(rules) {
      const { attributeValue = {} } = this;
      if (!attributeValue) return;
      const extArr = rules.map(r => r?.matchColumn);
      const extMap = {};
      for (const p of extArr) {
        extMap[p] = attributeValue[p];
      }
      for (const [key, val] of Object.entries(extMap)) {
        for (const rule of rules) {
          //首次加载执行赋值，非首次则不再重复赋值
          if (key == rule.matchColumn && this.isFirst) {
            //处理复选框valu类型检查必须为array
            if (rule.type == "checkbox" && !rule.value && !val) {
              rule.value = [];
            } else if (rule.type == "checkbox" && rule.value) {
              rule.value = JSON.parse(val);
            } else {
              rule.value = val;
            }
            //处理复选框valu类型检查必须为array
          } else if (rule.type == "checkbox" && !rule.value) {
            rule.value = [];
          }
        }
      }
    },
    getTemplateHandler() {
      const vm = this;
      const { userInfo } = $store.state[CoreModuleName];
      let { templateType, templateId } = this;
      if (!templateType) {
        templateType = window.$app && window.$app.$route.path;
        if (templateType) {
          templateType = templateType.replace(/\//g, "");
        }
      }

      const all = [
        getTemplateList({
          templateCategory: templateType,
          productCode: "", // currentRole.productCode 2.0 中没有产品的概念， 此处的productCode有待验证是否需要传
          tenantCode: userInfo.tenantCode
        })
      ];

      if (templateId) all.push(templateDetail(templateId));
      Promise.all(all).then(res => {
        const [list, cur = {}] = res;
        const arr = [...list.data, cur.data || {}];
        const obj = {};
        vm.ruleDatas = arr.filter(d => {
          if (d.id && !obj[d.id]) {
            obj[d.id] = true;
            return true;
          }
        });
        if (vm.ruleDatas.length > 0) {
          // vm.ruleDataVal = templateId || vm.ruleDatas[0].id;
          vm.ruleDataVal = templateId || "";
          vm.changeRule(vm.ruleDataVal);
          this.hasExpandAttr = true;
        } else {
          this.$emit("update:fApi", null);
          this.hasExpandAttr = false;
        }
      });
    },
    changeRule(val) {
      if (val != this.templateId){
         this.isFirst = false
      }else {
         this.isFirst = true
      };
      const target = this.ruleDatas.find(rule => rule.id === val);
      if (target) {
        this.mergGlobal(target.attributeContent.template);
      }
      this.$emit("update:templateId", val);
    },
    mergGlobal(val) {
      const { global = {} } = this.options;
      // 合并全局设置
      this.setGlobalConfig(val, global);
    },
    // 当拓展属性created时，拓展属性为空模板，显示提示
    getInitTemplateId() {
      if(this.templateId) {
        this.isShowTip = true
      }
    }
  }
};
</script>

<style lang="less">
.pigeonhole {
  display: inline-block;
  color: #bcbcbc !important;
}
.extendedAttrTitle {
  font-size: 14px;
  font-weight: bold;
  border-bottom: 0 !important;
  line-height: 14px !important;
  margin-bottom: 20px;
}
.common-fc {
  width: 100%;
}
.common-fc .form-create {
  padding: 0;
  margin: 0 -8px;
}
.create-form-wrap {
  .ivu-col {
    padding: 0 8px;
  }
  .ivu-form-item {
    display: flex;
    justify-content: space-between;
    .ivu-form-item-label {
      width: auto !important;
      min-width: 69px !important;
      max-width: 188px !important;
    }
    .ivu-form-item-content {
      margin-left: 0 !important;
      flex: 1;
      .ivu-input-number {
        width: 100% !important;
      }
    }
  }
}
.create-form-wrap90 {
  .ivu-form-item {
    display: flex;
    justify-content: space-between;
    .ivu-form-item-label {
      width: auto !important;
      min-width: 90px !important;
      max-width: 152px !important;
    }
    .ivu-form-item-content {
      margin-left: 0 !important;
      flex: 1;
      .ivu-input-number {
        width: 100% !important;
      }
    }
  }
}
.extendClass {
  border: 1px solid #eee;
  padding: 20px;
  margin-left: 0 !important;
}
.myForm {
  .ivu-form-item {
    .ivu-form-item-label {
      width: 68px !important;
    }
    .ivu-form-item-content {
      margin-left: 70px !important;
    }
  }
}
</style>